package com.example.androidproject.app;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager2.widget.ViewPager2;

import android.annotation.SuppressLint;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.androidproject.base.BaseFragment;
import com.example.androidproject.R;
import com.example.androidproject.base.ConnectionChangeReceiver;
import com.example.androidproject.movie.fragment.MovieFragment;
import com.example.androidproject.my.fragment.MyFragment;
import com.example.androidproject.novel.fragment.NovelFragment;
import com.example.androidproject.utils.GlobalVariable;
import com.example.androidproject.utils.StatusBarUtil;
import com.example.androidproject.utils.Tool;
import com.example.androidproject.wallpaper.fragment.WallpaperFragment;

import java.util.ArrayList;

public class MainActivity extends FragmentActivity implements View.OnClickListener {
    private final String TAG = "GGSTUDY";
    ViewPager2 viewPager2;
    private LinearLayout llMovie, llNovel, llWallpaper, llMy, ll_nav_box;
    private ImageView ivMovie, ivNovel, ivWallpaper, ivMy, ivCurrent;
    private ArrayList<BaseFragment> fragments;
    private int position;
    private Fragment tempFragemnt;
    private TextView nav_tv, login_tv;
    private LinearLayout rl_activity;
    private ConnectionChangeReceiver myReceiver;
    private String previousPosition = null;
    private FragmentManager mFm;
    private long recordTime;
    private long currentTime;


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int position = intent.getIntExtra("position", 0);
        if (position == 3) {
            changTab(R.id.ll_my);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 注册网络监听
        registerReceiver();
        //
        rl_activity = findViewById(R.id.rl_activity);
        //
        //设置顶部状态栏为透明
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);

        // 获取状态栏高度
        GlobalVariable.statusHeight = StatusBarUtil.getStatusBarHeight(getApplicationContext());

        // 获取 sp 拿到 token 以及上次记录token的时间并计算 大于10小时 则说明此token失效
        aboutTokenEvent();

        // 设置nav栏
        setNav();

        //
        /**
         * 例如在 320 * 480 尺寸为 3.2 英寸的手机 ，对应的像素密度应该为 160dpi 对应的像素比例应该是 1.0也就是 1dp = 1sp = 1px
         *
         * 而在 480 * 1280 尺寸为 4.7英寸的手机中，对应的像素密度为 320dpi 对应的像素比例应该是2.0 也就是 1dp = 1sp = 2px
         */
        // 获取缩放比例
        DisplayMetrics displayMetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        GlobalVariable.scaledDensity = displayMetrics.scaledDensity;

        // 获取屏幕宽高
        GlobalVariable.screenWidth = displayMetrics.widthPixels;
        GlobalVariable.screenHeight = displayMetrics.heightPixels;
        // 初始化Tab布局
        initTabView();
        // 初始化页面
        initPage();
        // 断网重连
        reConnection();
        // 首次进入执行
        /**
         * 第一次进入app要显示第一个fragment
         */
        if (previousPosition == null) {
            BaseFragment baseFragment = getFragment(0);
            switchFragment(tempFragemnt, baseFragment);
        }
    }

    // token验证有效性相关事件
    private void aboutTokenEvent() {
        SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
        GlobalVariable.token = sp.getString("token", "");
        recordTime = sp.getLong("recordTime", 0);
        currentTime = System.currentTimeMillis();
        long currentHour = (currentTime - recordTime) / 1000 / 60 / 60;
        Log.d(TAG, "aboutTokenEvent: " + recordTime);
        if (currentHour >= 10) {
            SharedPreferences.Editor edit = sp.edit();
            GlobalVariable.token = "";
            edit.putString("token", "");
            edit.apply();
        }
    }

    // 断网重连相关事件
    private void reConnection() {
        Intent intent = getIntent();
        previousPosition = intent.getStringExtra("position");
        if (previousPosition != null) {
            int previousPosition1 = Integer.parseInt(previousPosition);
            position = previousPosition1;
            if (previousPosition1 != -1) {
                if (previousPosition1 == 0) {
                    changTab(R.id.ll_movie);
                }
                if (previousPosition1 == 1) {
                    onClick(llNovel);
                }
                if (previousPosition1 == 2) {
                    changTab(R.id.ll_wallpaper);
                }
                if (previousPosition1 == 3) {
                    changTab(R.id.ll_my);
                }
            }
        }
    }

    // 设置 nav导航栏
    private void setNav() {
        ll_nav_box = findViewById(R.id.ll_nav_box);
        nav_tv = findViewById(R.id.nav_tv);
        login_tv = findViewById(R.id.login_tv);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        layoutParams.setMargins(0, (int) GlobalVariable.statusHeight, 0, 0);
        ll_nav_box.setLayoutParams(layoutParams);

        login_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changTab(R.id.ll_my);
            }
        });
        nav_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "onClick: " + "搜索");
                Toast.makeText(getApplicationContext(), "搜索", Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void initPage() {
        fragments = new ArrayList<>();
        fragments.add(new MovieFragment());
        fragments.add(new NovelFragment());
        fragments.add(new WallpaperFragment());
        fragments.add(new MyFragment());
    }

    private void initTabView() {
        llMovie = findViewById(R.id.ll_movie);
        llMovie.setOnClickListener(this);

        llNovel = findViewById(R.id.ll_novel);
        llNovel.setOnClickListener(this);

        llWallpaper = findViewById(R.id.ll_wallpaper);
        llWallpaper.setOnClickListener(this);

        llMy = findViewById(R.id.ll_my);
        llMy.setOnClickListener(this);

        ivMovie = findViewById(R.id.iv_movie);
        ivNovel = findViewById(R.id.iv_novel);
        ivWallpaper = findViewById(R.id.iv_wallpaper);
        ivMy = findViewById(R.id.iv_my);

        ivMovie.setSelected(true);
        ivCurrent = ivMovie;
    }

    @Override
    public void onClick(View v) {
        changTab(v.getId());
    }

    @SuppressLint("NonConstantResourceId")
    private void changTab(int id) {
        ivCurrent.setSelected(false);
        switch (id) {
            case R.id.ll_movie:
                position = 0;
            case 0:
                ivMovie.setSelected(true);
                ivCurrent = ivMovie;
                break;
            case R.id.ll_novel:
                position = 1;
            case 1:
                ivNovel.setSelected(true);
                ivCurrent = ivNovel;
                break;
            case R.id.ll_wallpaper:
                position = 2;
            case 2:
                ivWallpaper.setSelected(true);
                ivCurrent = ivWallpaper;
                break;
            case R.id.ll_my:
                position = 3;
            case 3:
                ivMy.setSelected(true);
                ivCurrent = ivMy;
                break;
            default:
                position = 0;
                break;
        }
        // 当点击是我的页面时 将头部导航栏隐藏
        if (position == 3) {
            ll_nav_box.setVisibility(View.GONE);
        } else {
            ll_nav_box.setVisibility(View.VISIBLE);
        }
        BaseFragment baseFragment = getFragment(position);
        /**
         * 第一个参数 上次显示
         * 第二个参数 当前显示
         */
        switchFragment(tempFragemnt, baseFragment);
    }

    private BaseFragment getFragment(int position) {
        if (fragments != null && fragments.size() > 0) {
            BaseFragment baseFragment = fragments.get(position);
            return baseFragment;
        }
        return null;
    }

    private void switchFragment(Fragment fromFragment, BaseFragment nextFragment) {
        /**
         * 缓存的 -> 上一次显示的，和当前要显示的 不一样 才会执行下面的代码
         * 否则就是  上一次和当前是一样的，那么就不需要执行
         */
        if (tempFragemnt != nextFragment) {
            tempFragemnt = nextFragment;
            if (nextFragment != null) {
                // 交易
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                //判断 nextFragment 是否添加
                if (!nextFragment.isAdded()) {
                    //隐藏当前 Fragment
                    if (fromFragment != null) {
                        transaction.hide(fromFragment);
                    }
                    transaction.add(R.id.frame, nextFragment).commit();
                } else {
                    //隐藏当前 Fragment
                    if (fromFragment != null) {
                        transaction.hide(fromFragment);
                    }
                    transaction.show(nextFragment).commit();
                }
            }
        }

    }

    // 注册网络监听
    private void registerReceiver() {

        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        myReceiver = new ConnectionChangeReceiver() {
            @Override
            protected void onDisconnected() {
                GlobalVariable.netFlag = 0;
                Log.d(TAG, "onDisconnected: 断开连接了");
            }

            @Override
            protected void onConnected() {
                if (GlobalVariable.netFlag == 0) {
                    Log.d(TAG, "onConnected: 重新连接上了");
                    refresh();
                    GlobalVariable.netFlag = -1;
                }
            }
        };
        this.registerReceiver(myReceiver, filter);
    }

    // 卸载网络监听
    private void unregisterReceiver() {
        this.unregisterReceiver(myReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver();
    }

    public void refresh() {
        finish();
        Intent intent = new Intent(MainActivity.this, MainActivity.class);
        String str = Integer.toString(position);
        intent.putExtra("position", str);
        startActivity(intent);
    }

}